package org.ala.tiktools.rocketmq.producer;

import com.oracle.jrockit.jfr.Producer;
import org.ala.tiktools.rocketmq.annotations.Tag;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.Map;


/**
 * @author ala
 * @date 2024-12-05 12:46
 */
public class ProducerServiceInvocationHandler implements InvocationHandler {


    /**
     *
     */
    protected Map<Method, ProducerExecutor> executorMapper;

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        ProducerExecutor executor = executorMapper.get(method);
        if (executor == null) {
            return method.invoke(args);
        }

        //  发送消息
        executor.send(args, tagIndex(method));
        return null;
    }


    protected Map<Method, Integer> tagIdxMemo = new HashMap<>();
    /**
     *  取method中@Tag注解的下标
     */
    protected int tagIndex(Method method) {
        Integer idx = tagIdxMemo.get(method);
        if (idx != null) {return idx;}

        Parameter[] params = method.getParameters();
        for (int i = 0 ; i < params.length ; i++) {
            Tag tag = params[i].getAnnotation(Tag.class);
            if (tag != null) {
                tagIdxMemo.put(method, i);
                return i;
            }
        }
        tagIdxMemo.put(method, -1);
        return -1;
    }

}
